package com.authorize.quartz.task;

import com.alibaba.fastjson2.JSONObject;
import com.authorize.common.exception.TClientException;
import com.authorize.common.utils.PayUtils;
import com.authorize.common.utils.RedisUtils;
import com.authorize.system.domain.AAuth;
import com.authorize.system.domain.AGood;
import com.authorize.system.domain.AOrder;
import com.authorize.system.domain.APayConfig;
import com.authorize.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.authorize.common.utils.StringUtils;

import java.util.*;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask
{

    @Autowired
    private IAOrderService aOrderService;

    @Autowired
    private IAPayConfigService aPayConfigService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IAGoodService aGoodService;

    @Autowired
    private IAAuthService aAuthService;

    /**
     * 订单同步
     */
    public void syncOrder(){
        //同步待支付订单
        AOrder aOrder = new AOrder();
        aOrder.setStatus(1);
        List<AOrder> payList = aOrderService.selectAOrderList(aOrder);
        for (int i = 0; i < payList.size(); i++) {
            try{
                //查询支付通道
                APayConfig aPayConfig = aPayConfigService.selectAPayConfigById(payList.get(i).getPayId());
                if(aPayConfig != null){
                    JSONObject params = new JSONObject();
                    params.put("outTradeNo",payList.get(i).getOutTradeNo());
                    Map<String,String> headers = new HashMap<>();
                    headers.put("appid",aPayConfig.getAppId());
                    String p = JSONObject.toJSONString(params);
                    String sign = PayUtils.getSign(p,aPayConfig.getSginKey());
                    headers.put("sign",sign);
                    String payUrl = configService.selectConfigByKey("sys.payUrl");
                    //请求查询接口
                    String result = PayUtils.doPost(payUrl + "/open/api/query",p,headers);
                    //解析结果
                    JSONObject data = JSONObject.parseObject(result).getJSONObject("data");
                    if(data.getInteger("status") == 2){
                        //先判断是什么类型授权
                        AGood aGood = aGoodService.selectAGoodById(payList.get(i).getGoodId());
                        if(aGood != null){
                            //单线程处理业务
                            RedisUtils.lock(payList.get(i).getOutTradeNo(),30000,payList.get(i).getOutTradeNo());
                            try{
                                AAuth aAuth = new AAuth();
                                aAuth.setAuthEntryId(aGood.getEntryId());
                                aAuth.setAuthType(aGood.getAuthType());
                                if(aGood.getAuthType() == 1){
                                    aAuth.setAuthValue(payList.get(i).getAuthValue());
                                }
                                //到期时间计算 当前时间+月份
                                aAuth.setEndTime(subMonth(new Date(),Integer.parseInt(aGood.getEffectiveTime().toString())));
                                aAuth.setStatus(1);
                                aAuth.setCreateBy(payList.get(i).getCreateBy());
                                AOrder nAOrder = aOrderService.selectAOrderByOutTradeNo(data.getString("outTradeNo"));
                                if(nAOrder != null && nAOrder.getStatus() == 1){
                                    //查询订单如果成功了，则不处理，查询授权信息，如果成功了也不处理
                                    aAuth.setAuthNo(nAOrder.getOutTradeNo().replace("AUTH",""));
                                    AAuth auth = aAuthService.insertAAuthLock(aAuth);
                                    //更新订单信息
                                    nAOrder.setAuthId(auth.getId());
                                    nAOrder.setAuthNo(auth.getAuthNo());
                                    nAOrder.setTransactionTime(data.getDate("transactionTime"));
                                    nAOrder.setUpdateTime(new Date());
                                    nAOrder.setStatus(2);
                                    aOrderService.updateAOrder(nAOrder);
                                }
                            }catch (Exception e){
                                throw new TClientException(e.getMessage());
                            }finally {
                                RedisUtils.releaseLock(payList.get(i).getOutTradeNo(),payList.get(i).getOutTradeNo());
                            }
                        }
                    }else{
                        payList.get(i).setStatus(data.getInteger("status"));
                        payList.get(i).setUpdateTime(new Date());
                        aOrderService.updateAOrder(payList.get(i));
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //同步退款处理中订单
        aOrder.setStatus(4);
        List<AOrder> refundList = aOrderService.selectAOrderList(aOrder);
        for (int i = 0; i < refundList.size(); i++) {
            try{
                //查询支付通道
                APayConfig aPayConfig = aPayConfigService.selectAPayConfigById(refundList.get(i).getPayId());
                if(aPayConfig != null){
                    JSONObject params = new JSONObject();
                    params.put("outTradeNo",refundList.get(i).getOutTradeNo());
                    Map<String,String> headers = new HashMap<>();
                    headers.put("appid",aPayConfig.getAppId());
                    String p = JSONObject.toJSONString(params);
                    String sign = PayUtils.getSign(p,aPayConfig.getSginKey());
                    headers.put("sign",sign);
                    String payUrl = configService.selectConfigByKey("sys.payUrl");
                    //请求查询接口
                    String result = PayUtils.doPost(payUrl + "/open/api/query",p,headers);
                    //解析结果
                    JSONObject data = JSONObject.parseObject(result).getJSONObject("data");
                    if(data.getInteger("status") == 5){
                        //退款成功
                        refundList.get(i).setStatus(5);
                        refundList.get(i).setRefundTime(new Date());
                        refundList.get(i).setUpdateTime(new Date());
                        aOrderService.updateAOrder(refundList.get(i));
                    }else{
                        refundList.get(i).setStatus(data.getInteger("status"));
                        refundList.get(i).setUpdateTime(new Date());
                        aOrderService.updateAOrder(refundList.get(i));
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    /**
     * 授权到期检测
     */
    public void authEndTime(){
        aAuthService.updateAAuthEndTime();
    }



    /****
     * 增加月份时间
     * @param date 日期(2017-04-13)
     * @return 2017-05-13
     * @throws Exception
     */
    private Date subMonth(Date date,Integer month) throws Exception {
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(date);
        rightNow.add(Calendar.MONTH, month);
        Date dt1 = rightNow.getTime();
        return dt1;
    }
}
